package org.forum.dao.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.forum.dao.UserDao;
import org.forum.dao.base.BaseDaoImpl;
import org.forum.domain.User;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao<User> {

	Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);

	@Override
	public User findUserByUsernameAndPassword(User user) {
		String hql = "SELECT en FROM User en WHERE en.username=?0 AND en.userPass=?1";
		List<User> users = find(hql, user.getUsername(), user.getUserPass());
		if (users.size() != 0) {
			return users.get(0);
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("users.size == 0");
			}
			return null;
		}
	}

	@Override
	public User findUserByUsername(User user) {
		String sql = "SELECT en FROM User en WHERE en.username=?0";
		List<User> users = find(sql, user.getUsername());
		if (users.size() != 0) {
			return users.get(0);
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("users.size == 0");
			}
			return null;
		}
	}

	@Override
	public Serializable saveUser(User user) {
		return save(user);
	}

	@Override
	public User findUserById(int userId) {
		return (User) get(User.class, userId);
	}

	@Override
	public void updateUser(User user) {
		if (user.getUserId() == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("user.getUserId() == null");
			}
		}
		update(user);
	}

	@Override
	public Map<String, User> getUserInfoByIds(Map<String, String> userIds) {
		Map<String, User> userInfos = new HashMap<>();
		Iterator iter = userIds.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			userInfos.put(key, findUserById(Integer.parseInt(value)));
		}
		return userInfos;
	}

}
